package org.grow.cooldown.ScoreModule;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

@Service
public class SessionAuthIntercepter implements HandlerInterceptor {

    private static ThreadLocal<String> auth = new ThreadLocal<>();
    public static String getAuth() {
        return auth.get();
    }

    public static void setAuth(String a) {
        auth.set(a);
    }

    @Autowired
    RedisTemplate redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Cookie credential = null;
        for (Cookie cookie : request.getCookies()) {
            if (LoginIntercepter.redisId.equals(cookie.getName())){
                credential=cookie;
            }
        }
        if (credential == null) throw new LoginIntercepter.LoginExcpt(1010,
                "no cookie no login no auth pass, Please login first");
        String key = credential.getValue();
        Object o = redisTemplate.opsForValue().get(key);
        if (o == null ) throw new LoginIntercepter.LoginExcpt(1011,
                "redis miss this key ,maybe expired or logout");
        Map<String, Object> m =(Map<String,Object>)o;
        List roles = (List) m.get("role");
        roles.add(0,m.get("username"));
        String rolesex = String.join("-", roles);
        auth.set(rolesex);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        auth.remove();
    }
}
